package org.lql.shop.cloud.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.lql.shop.cloud.IOrderService;
import org.lql.shop.cloud.IShopService;
import org.lql.shop.cloud.entity.ShopCartEntity;
import org.lql.shop.cloud.mapper.ShopCartMapper;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author: lql
 * @date: 2022/7/2 22:22
 * @description: 购物车服务接口
 */
@DubboService(group = "jike-shop", version = "1.0.0", protocol = "dubbo", cluster = "failover", retries = 3, loadbalance = "roundrobin", actives = 100)
@Slf4j
public class ShopServiceImpl implements IShopService {

    @Autowired
    private ShopCartMapper shopCartMapper;

    @DubboReference(group = "jike-shop", version = "1.0.0", protocol = "dubbo", check = false, timeout = 3000)
    private IOrderService orderService;

    @Override
    public String placeOrder(Long cartId) {
        ShopCartEntity shopCartEntity = shopCartMapper.selectById(cartId);
        return orderService.createOrder(shopCartEntity.getGoodId());
    }

    @Override
    public String optimistic(Long cartId) {
        // 获取购物车信息
        ShopCartEntity cartA = shopCartMapper.selectById(cartId);
        ShopCartEntity cartB = shopCartMapper.selectById(cartId);
        // 更新A购物车信息
        cartA.setGoodNum(cartA.getGoodNum() + 50);
        shopCartMapper.updateById(cartA);
        // 更新B购物车信息
        cartB.setGoodNum(cartB.getGoodNum() - 30);
        int res = shopCartMapper.updateById(cartB);
        if (res == 0) {
            //扣减失败，重新扣减
            ShopCartEntity cartC = shopCartMapper.selectById(cartB.getCartId());
            cartC.setGoodNum(cartC.getGoodNum() - 30);
            shopCartMapper.updateById(cartC);
        }
        ShopCartEntity cartEntity = shopCartMapper.selectById(cartId);
        log.info("最终购物车数量：{}", cartEntity.getGoodNum());
        return cartEntity.toString();
    }
}
